import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../MainLayout.vue'
import DishManagement from '../views/DishManagement.vue'
import DishCategoryManagement from '../views/DishCategoryManagement.vue'
import OrderManage from '../views/OrderManage.vue'
import Statistics from '../views/Statistics.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      { path: '', redirect: '/dish-management' },
      { path: 'dish-management', component: DishManagement },
      { path: 'dish-category-management', component: DishCategoryManagement },
      { path: 'order-manage', component: OrderManage },
      { path: 'statistics', component: Statistics }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：未登录则跳转到登录页
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router